<template>
    <div>
        <page-header-wrapper></page-header-wrapper>
        <a-card style="margin-top: 20px">
            <div class="table-page-search-wrapper">
                <a-form :form="searchForm" layout="inline">
                    <a-row :gutter="48">
                        <SearchFormItems :searchKeys="StaffListSearchKeys" :advanceVal="advanced" :getDataWithKey="getDataWithKey">
                        </SearchFormItems>
                        <a-col :md="(!advanced && 8) || 6" :sm="6" class="advanced_butns">
                            <span class="table-page-search-submitButtons" :style="
                                (advanced && { float: 'right', overflow: 'hidden' }) || {}
                            ">
                                <a-button @click="reset">重置</a-button>
                                <a-button type="primary" @click="search">查询</a-button>
                                <a @click="toggleAdvanced">
                                    {{ advanced ? '收起' : '展开' }}
                                    <a-icon :type="advanced ? 'up' : 'down'" />
                                </a>
                            </span>
                        </a-col>
                    </a-row>
                </a-form>
            </div>
        </a-card>
        <div class="cont_box">
            <div class="table_header flex-between">
                <div class="table_name">{{pageTitle}}</div>
                <div class="table_butns flex-end">
                    <a-button type="primary" icon="plus" @click="showModal('add',null)">新增</a-button>
                </div>
            </div>
            <a-table :columns="StaffListColumn" :dataSource="dataSource" :pagination="pagination" :rowKey="(it,index) => index +it.id " :loading="loading" binvested @change="tableSort">
                <a-badge slot="active" slot-scope="text" :status="text.active == 1 ?'success':'error'" :text="getStatusName(text.active)" />
                <span slot="operation" slot-scope="text, record">
                    <a-button size="small" type="link" @click="statusUpdate(record)">
                        {{text.active == 1 ?'禁用':'启用'}}
                    </a-button>
                    <a-button size="small" type="link"  @click="showModal('edit',record)">
                        编辑
                    </a-button>
                    <a-button size="small" type="link"  @click="checkPwd(record)">
                        查看密码
                    </a-button>
                </span>
            </a-table>
            <pagination :total="total" :page.sync="page" :size.sync="size" :onPageSizeChange="onPageSizeChange" :onShowSizeChange="onShowSizeChange" />
            <a-modal :title="modalType == 'edit'?'编辑':'新增'" v-model="editVisible" destroyOnClose @ok="sureModal" width="600px">
                <div class="modal_body_cont">
                    <a-form :form="modalForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
                        <modalFormItem :searchKeys="modalType == 'add' ? StaffModalKeys : StaffModalKeys.filter(item=>{return item.key !='pwd'})" :getDataWithKey="getDataWithKey"></modalFormItem>
                    </a-form>
                </div>
            </a-modal>
            
        </div>
    </div>
    </template>
    
    <script>
    import moment from 'moment'
    import {
        StaffListSearchKeys, StaffListColumn, StaffModalKeys,
    } from './config'
    import {
        staffList, staffUpdate, staffAdd, staffActive, staffPwdScan,companyList, companyAllList, roleListApi,
    } from '@/api/company'
    
    export default {
        name: 'CompanyStaff',
        data() {
            return {
                pageTitle:'',
                StaffListSearchKeys,
                StaffListColumn,
                // 高级搜索 展开/关闭
                advanced: false,
                dataSource: [],
                pagination: false,
                page: 1,
                size: 50,
                total: 0,
                loading: false,
                editVisible: false,
                searchForm:this.$form.createForm(this, { name:'client_list_search' }),
                modalForm: this.$form.createForm(this, {
                    name: "client_list_modal"
                }),
                StaffModalKeys,
                clientId:'',
                sortString:'createTime,desc',
                modalType:'add',
                statusArrs:[{key:'1',value:'正常'},{key:'0',value:'禁用'}],
                companyLists:[],
                allCompanyList: [],
                roleList: [],
            }
        },
        computed: {
            getDataWithKey() {
                return key => {
                    switch (key) {
                        case "active":
                            return this.statusArrs;
                        case "companyId":
                            return this.allCompanyList;
                        case "roleCodes": 
                            return this.roleList;
                        default:
                            return [];
                    }
                };
            },
        },
        created() {
            this.pageTitle = this.$route?.meta?.title
            this.getCompanyList()
            this.getList();
            this.getRoleList();
        },
        methods: {
            async getRoleList() {
                let res = await roleListApi();
                let clist = res?.data || [], listArr = [];
                clist.map(item => {
                    let obj = {key: item.val, value: item.key}
                    listArr.push(obj)
                })
                this.roleList = listArr
            },
            async getAllCompanyList() {
                let res = await companyAllList();
                // this.allCompanyList = res.data
                let clist = res?.data || [], listArr = [];

                clist.map(item => {
                    let obj = {key: item.id, value: item.name}
                    listArr.push(obj)
                })
                this.allCompanyList = listArr
                console.log(listArr)
            },
            async getCompanyList(){
                let param = {
                    // orders: [{column: "create_time", asc: false}],
                    pageNum: 1,
                    pageSize: 300
                }, res = await companyList(param);
                let temList = res?.data?.list || [],listArr = []
                temList.map(item=>{
                    let obj = {}
                    obj.key = item.id
                    obj.value = item.name
                    listArr.push(obj)
                })
                this.companyLists = listArr || []
                console.log('companyList',listArr)
            },
            search() {
                this.page = 1;
                this.getList();
            },
            reset() {
                this.searchForm.resetFields();
                this.page = 1;
                this.getList();
            },
            onPageSizeChange(page, size) {
                this.page = page;
                this.getList(page, size);
            },
            onShowSizeChange(page, size){
                this.page = page;
                this.size = size;
                this.getList(page, size);
            },
            statusUpdate({id,active}){
                this.$confirm({
                    title: `确定要${active == 1?'禁用':'启用'}吗？`,
                    content: '',
                    okText: `${active == 1?'禁用':'启用'}`,
                    okType: 'danger',
                    cancelText: '取消',
                    onOk: () => {
                        staffActive({id,active: active == 1 ? 0 :1}).then(res =>{
                            if(res?.success){
                                this.$message.success('操作成功')
                                this.getList()
                            }else{
                                this.$message.error(res?.message)
                            }
                        })
                    },
                })
            },
            getStatusName(status){
                let tem = this.statusArrs.filter(item =>{return item.key == status}); 
                if(tem && tem.length>0){
                    return tem[0]?.value
                }else{
                    return ''
                }
            },
            cameltoLine(value){
                return value.replace(/([A-Z])/g,"_$1").toLowerCase()
            },
            tableSort( page,filters, {field,order}){
                if( field == 'createTime'
                ){
                    this.sortString = order ? field +',' + (order=="descend"?'desc':'asc') : ''
                    this.getList(1)
                }
            },
            // 获取列表
            async getList(currentPage, currentSize) {
                this.loading = true
                const { page, size, sortString } = this;
                let sort = sortString.split(',')
                this.searchForm.validateFields(async (err, values) => {
                    if (!err) {
                        let params = {
                            pageNum: (currentPage) || (page),
                            pageSize: currentSize || size,
                            ...values,
                            sort: this.cameltoLine(sort[0]), 
                            order:sort[1],
                            createTime:moment(values.createTime).format('YYYY-MM-DD hh:mm:ss')
                        };
                        const res = await staffList(params)
                        if(res?.success){
                            this.total = res?.data?.total || 0;
                            this.dataSource = res?.data?.list || []
                        }else{
                            this.$message.error(res?.message)
                        }
                        this.loading = false
                    } else{
                        this.loading = false
                    }
                })
            },
            checkPwd({id}){
                staffPwdScan({id}).then(res =>{
                    if(res?.success){
                        this.$info({
                            title: '密码',
                            content:`${res?.data}`,
                            onOk() {

                            },
                        });
                    }else{
                        this.$message.error(res?.message)
                    }
                })
            },
            showModal(type,record) {
                this.modalType = type
                this.editVisible = true
                if(type == 'add'){
                    this.clientId = ''
                    this.modalForm.resetFields()
                }else if(type == 'edit'){
                    this.getAllCompanyList()
                    let {id,userName, employeeName,active,remark,email} = record
                        this.clientId = id
                        this.$nextTick(() => {
                        setTimeout(() => {
                            this.modalForm.setFieldsValue({ userName,employeeName,active,remark,email})
                        },400)
                    });
                }
            },
            sureModal() {
                let { clientId, modalType } = this
                    this.modalForm.validateFields(async (err,values) => {
                        if(!err){
                            let params = {
                                ...values,
                                id:clientId,
                            }
                            let res = modalType == 'add' ? await staffAdd(params) : await staffUpdate(params);
                            if(res?.success){
                                this.$message.success(`${modalType == 'add' ?'添加':'编辑'}成功`)
                                this.getList()
                            }else{
                                this.$message.error(res?.message)
                            }
                            this.clientId = ''
                            this.editVisible = false
                        }
                    })
            },
            toggleAdvanced() {
                this.advanced = !this.advanced;
            },
        },
    };
    </script>
    